<template>
  <div class="search-container">
    <h2>题目搜索</h2>
    <form @submit.prevent="handleSearch">
      <div class="form-row">
        <div class="form-group">
          <label for="difficulty">难度:</label>
          <select v-model="searchCriteria.difficulty" id="difficulty" class="select-box">
            <option value="">所有</option>
            <option v-for="(level) in difficulties" :key="level.label" :value="level.value">
              {{ level.label }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label for="tag">标签:</label>
          <div class="tag-select-container" @click="toggleTagSelector">
            <span class="tag-select-label">选择标签</span>
          </div>
        </div>

        <div class="form-group">
          <label for="keyword">关键字:</label>
          <input type="text" v-model="searchCriteria.keyword" id="keyword" placeholder="请输入关键字" autocomplete="off"/>
        </div>
      </div>

      <div class="form-row options-row">
        <div class="form-group">
          <label for="order">排序:</label>
          <select v-model="sortOrder" id="order" class="select-box">
            <option value="problem_number_asc">题号升序</option>
            <option value="problem_number_desc">题号降序</option>
            <option value="difficulty_asc">难度升序</option>
            <option value="difficulty_desc">难度降序</option>
          </select>
        </div>

        <div class="form-group show-tags">
          <label for="showTags">显示标签:</label>
          <input type="checkbox" v-model="showTags" id="showTags"/>
        </div>
      </div>

      <!-- 显示已选择标签名称 -->
      <div class="selected-tags">
        <span v-for="(tag, index) in selectedTagNames" :key="index" class="tag selected">
          {{ tag }}
        </span>
      </div>

      <button type="submit">搜索</button>
    </form>

    <div v-if="searchResults.length">
      <h3>搜索结果:</h3>
      <table>
        <thead>
          <tr>
            <th>题号</th>
            <th>题目名称</th>
            <th>难度</th>
            <th>通过率</th>
            <th>提交次数</th>
            <th v-if="showTags">标签</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in paginatedResults" :key="index">
            <td>
              <a :href="getProblemLink(item.problem_number)" target="_blank">
                {{ item.problem_number }}
              </a>
            </td>
            <td>{{ item.problem_name }}</td>
            <td>{{ item.difficulty }}</td>
            <td>{{ item.acceptance_rate.toFixed(3) }}</td>
            <td>{{ item.submission_count }}</td>
            <td v-if="showTags">
              <div class="tag-container">
                <span v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="tag">
                  {{ tag.tag_name }}
                </span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} 页 / {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      </div>
    </div>

    <div v-if="showTagSelector" class="tag-selector-modal">
      <div class="tag-selector-content">
        <h4>选择标签</h4>
        <div class="tag-selector">
          <div class="tag-container">
            <span
              v-for="(tag, tagIndex) in tags"
              :key="tagIndex"
              :class="['tag', { selected: selectedTags.includes(tag.index) }]"
              @click="toggleTag(tag.index)"
            >
              {{ tag.tag_name }}
            </span>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="confirmSelection">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from '@/axios';

export default {
  data() {
    return {
      searchCriteria: {
        difficulty: '',
        tag: '',
        keyword: ''
      },
      searchResults: [],
      paginatedResults: [],
      currentPage: 1,
      pageSize: 40,
      totalPages: 0,
      tags: [],
      showTags: false,
      showTagSelector: false,
      selectedTags: [], // 存储已选标签的索引
      selectedTagNames: [], // 存储已选标签的名称
      sortOrder: 'problem_number_asc',
      difficulties: [
        { value: "暂无评定", label: "暂无评定" },
        { value: "入门", label: "入门" },
        { value: "普及-", label: "普及-" },
        { value: "普及/提高-", label: "普及/提高-" },
        { value: "普及+/提高", label: "普及+/提高" },
        { value: "提高+/省选-", label: "提高+/省选-" },
        { value: "省选/NOI-", label: "省选/NOI-" },
        { value: "NOI/NOI+/CTSC", label: "NOI/NOI+/CTSC" }
      ]
    };
  },
  methods: {
    async fetchTags() {
      try {
        const response = await axios.get('/api/tag/algorithmtag');
        this.tags = response.data;
      } catch (error) {
        console.error('无法获取标签信息:', error);
      }
    },
    async handleSearch() {
      try {
        const params = {
          difficulty: this.searchCriteria.difficulty,
          keyword: this.searchCriteria.keyword,
        };

        if (this.selectedTags.length > 0) {
          params.tag = this.selectedTags.join(',');
        }

        const response = await axios.get('/api/search/data', { params });
        this.searchResults = response.data.problems;
        this.totalPages = Math.ceil(this.searchResults.length / this.pageSize);
        this.currentPage = 1;
        this.updatePaginatedResults();
      } catch (error) {
        console.error('搜索失败:', error);
      }
    },
    updatePaginatedResults() {
      const sortedResults = this.sortResults();
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedResults = sortedResults.slice(start, end);
    },
    sortResults() {
      return this.searchResults.sort((a, b) => {
        if (this.sortOrder === 'problem_number_asc') {
          return a.problem_number.localeCompare(b.problem_number);
        } else if (this.sortOrder === 'problem_number_desc') {
          return b.problem_number.localeCompare(a.problem_number);
        } else if (this.sortOrder === 'difficulty_asc') {
          return a.difficulty.localeCompare(b.difficulty);
        } else if (this.sortOrder === 'difficulty_desc') {
          return b.difficulty.localeCompare(a.difficulty);
        }
        return 0;
      });
    },
    toggleTag(tag) {
      if (this.selectedTags.includes(tag)) {
        this.selectedTags = this.selectedTags.filter(t => t !== tag);
      } else {
        this.selectedTags.push(tag);
      }
    },
    toggleTagSelector() {
      this.showTagSelector = !this.showTagSelector;
    },
    confirmSelection() {
      this.showTagSelector = false;
      this.selectedTagNames = this.selectedTags
        .map(tagIndex => {
          const tag = this.tags.find(t => t.index === tagIndex);
          return tag ? tag.tag_name : '';
        })
        .filter(tagName => tagName);
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.updatePaginatedResults();
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.updatePaginatedResults();
      }
    },
    getProblemLink(problemNumber) {
      return `https://www.luogu.com.cn/problem/${problemNumber}`;
    }
  },
  mounted() {
    this.fetchTags();
  }
};
</script>

<style scoped>
.search-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 30px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #ffffff;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
}

.form-row, .options-row {
  display: flex;
  justify-content: space-between;
  margin: 15px 30px;
}

.form-group {
  flex: 1;
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.form-group:last-child {
  margin-right: 0;
}

label {
  font-weight: 500;
  color: #444;
  margin-right: 10px;
}

input[type="text"], select.select-box {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  transition: border-color 0.3s;
}

input[type="text"]:focus, select.select-box:focus {
  border-color: #007bff;
  outline: none;
}

.show-tags {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.tag-select-container {
  cursor: pointer;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f2f2f2;
  font-size: 14px;
  color: #333;
  transition: background-color 0.3s;
}

.tag-select-container:hover {
  background-color: #e0e0e0;
}

.selected-tags {
  margin: 15px 0;
  display: flex;
  flex-wrap: wrap;
}

.selected-tags .tag {
  background-color: #007bff;
  color: white;
  border-radius: 15px;
  padding: 5px 10px;
  margin: 5px;
  font-size: 12px;
}

.tag-selector-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.tag-selector-content {
  background: #ffffff;
  padding: 25px;
  width: 800px;
  border-radius: 8px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  text-align: center;
}

.tag-selector {
  max-height: 300px;
  overflow-y: auto;
  margin: 20px 0;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag {
  background-color: #e0e0e0;
  color: #333;
  border-radius: 15px;
  padding: 5px 10px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.tag.selected {
  background-color: #007bff;
  color: white;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
}

button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

th, td {
  padding: 12px;
  text-align: left;
  border: 1px solid #ddd;
}

th {
  background-color: #f4f4f4;
  font-weight: 600;
}

a {
  font-weight: 500;
  color: #007bff;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination button {
  padding: 8px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.pagination button:disabled {
  background-color: #ddd;
  cursor: not-allowed;
}
</style>